package com.myapp.Activity.AirLink;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.myapp.Activity.BaseActivity;
import com.myapp.Data.NetState;
import com.myapp.R;
import com.myapp.View.SimpleToolbar;
import com.myapp.utils.PreferencesUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.myapp.Activity.MainActivity.INTENT_CHOOSE;

public class AirlinkChooseActivity extends BaseActivity {
    private static final String TAG = "AirlinkChooseActivity";
    private NetState netState;
    private int status;
    public static final String WIFI_NAME = "wifi_name";
    public static final String WIFI_PASSWORD = "wifi_password";
    public static final String AP_NAME = "ap_name";
    public static final String AIR_LINGKING = "0";
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION"};
    @BindView(R.id.toolbar_airLink_choose)
    SimpleToolbar toolbarAirLinkChoose;

    @BindView(R.id.iv_login_confirm)
    ImageView ivLoginConfirm;
    @BindView(R.id.tv_wifi_name)
    TextView tvWifiName;
    @BindView(R.id.et_password)
    EditText etPassword;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_airlink_choose);

        //检测是否有位置定位的权限
        int permission = ActivityCompat.checkSelfPermission(AirlinkChooseActivity.this,
                "android.permission.ACCESS_FINE_LOCATION");

        if (permission != PackageManager.PERMISSION_GRANTED) {
            try {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(AirlinkChooseActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Intent intent =getIntent();
        status = intent.getIntExtra(INTENT_CHOOSE,0);
        NetState.init(this.getApplicationContext());
        netState = NetState.getInstance();
        netState.registBroadcast();
        netState.getWifiManger();
        ButterKnife.bind(this);
        toolbarAirLinkChoose.setLeftIconClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        if (NetState.getInstance().isWifiConnected()) {
            WifiInfo info = NetState.getInstance().getCurrentWifiInfo();
            tvWifiName.setText(NetState.getInstance().getWIFISSID());
        }


//        String ss = String.valueOf(status);
//        Toast.makeText(getApplicationContext(),ss,Toast.LENGTH_SHORT).show();

        //获取ssid的第二个方法,不能用了， 只保存刷新功能
        NetState.getInstance().setWifiStateCallback(new NetState.WifiStateCallback() {
            @Override
            public void onWifiChange(WifiInfo info) {
                info = NetState.getInstance().getCurrentWifiInfo();
                tvWifiName.setText(NetState.getInstance().getWIFISSID());
                Log.i(TAG, "onWifiChange: "+info);

            }
        });

    }

    @OnClick(R.id.iv_login_confirm)
    void onClick(View view){
        switch (view.getId()){
            case R.id.iv_login_confirm:
                if (status==0) {
                    String ssid = tvWifiName.getText().toString();
                    String key = etPassword.getText().toString();
                    PreferencesUtil.getInstance(getApplicationContext()).putString(WIFI_NAME,ssid);
                    PreferencesUtil.getInstance(getApplicationContext()).putString(WIFI_PASSWORD,key);
                    Intent intent = new Intent(this,AirlinkingActivity.class);
                    intent.putExtra(AIR_LINGKING,0);
                    startActivity(intent);
                }

                if (status==1){
                    String ssid = tvWifiName.getText().toString() ;
                    String cutSsid = ssid.substring(0,2);
                    String psw = etPassword.getText().toString();
                    Log.i(TAG, "onClick: "+"ssid:"+ssid+" psw:"+psw);
                    if (psw.length()<8){
                        Toast.makeText(getApplicationContext(),"密码格式不对",Toast.LENGTH_SHORT).show();
                    }
                    else if(ssid.length()!=15||!cutSsid.equals("XP")) {
                        PreferencesUtil.getInstance(getApplicationContext()).putString(WIFI_NAME,ssid);
                        PreferencesUtil.getInstance(getApplicationContext()).putString(WIFI_PASSWORD,psw);
                        AlertDialog.Builder builder = new AlertDialog.Builder(AirlinkChooseActivity.this);
                        builder.setTitle("热点配网流程") //标题
                                .setMessage("1.点击确认，跳转设置 \n 2.连接热点 “XPG-GAgent”并且返回\n3.输入密码:123456789，点击下一步") //提示内容
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() { //确定
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("取消", null);
                        builder.show();
                    } else {
                        String apName = tvWifiName.getText().toString();
                        PreferencesUtil.getInstance(getApplicationContext()).putString(AP_NAME,apName);
                        Intent intent = new Intent(getApplicationContext(),AirlinkingActivity.class);
                        intent.putExtra(AIR_LINGKING,1);
                        startActivity(intent);
                    }
                }
                 break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        netState.unRegisterBroadcast();
    }




    private boolean isSDKAtLeastP() {
        return Build.VERSION.SDK_INT >= 28;
    }

}
